<?php
/**
 * @link https://www.leadshop.vip/
 * @copyright Copyright ©2020-2021 浙江禾成云计算有限公司
 */
namespace system\api;

use framework\common\AccessToken;
use framework\common\BasicController;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\ForbiddenHttpException;
use yii\web\ServerErrorHttpException;

/**
 * 后台用户管理器
 */
class AccountController extends BasicController
{

    /**
     * 后台登录
     * @return [type] [description]
     */
    public $modelClass2 = 'system\models\Roles';

    public function actionLogin()
    {
        $post = Yii::$app->request->post();
        $data = $this->modelClass::find()->where(['mobile' => $post['mobile'], 'password' => MD5($post['password'])])->one();
        if ($data) {
            //如果数据存在，则转数组
            $data = $data->toArray();
            //删除用户密码字段
            unset($data['password']);
            //获取Token数据
            $data['token_type']    = 'Bearer';
            $data['access_token']  = AccessToken::getToken($data['id']);
            $data['refresh_token'] = AccessToken::getToken($data['id'], 2);
            return $data;
        } else {
            Error('用户不存在或密码错误');
        }
    }

    /**
     * 后台登录
     * @return [type] [description]
     */
    public function actionLogout()
    {
        return null;
    }

    /**
     * 用户注册
     * @return [type] [description]
     */
    public function actionRegister()
    {

        //调用模型
        $model    = new $this->modelClass();
        $postData2 = Yii::$app->request->post();
        $postData = Yii::$app->request->post();
        if ($postData2['password']!=$postData2['repassword']) {
            Error('兩次輸入的密碼不一樣!');
        }
        if(strlen($postData['id'])>0) {
            //
            $databe = $this->modelClass::find()->where(['mobile' => $postData['mobile']])
                ->andWhere('id<>'.$postData['id'])->one();
            if ($databe) {
                Error('手機號碼已經註冊');
            }
            $data['mobile']=$postData['mobile'];
            $data['nickname']=$postData['nickname'];
            $data['name']=$postData['name'];
            $data['remark']=$postData['remark'];
            $data['store_id']=$postData['store_id'];
            $data['roles']='['.$postData['roles'].']';
            $data['password']= MD5($postData['password']);
            $data['showpassword']= $postData['password'];
            $result = $model::updateAll($data, ['id' => $postData['id']]);
            $model = $model::findOne($postData['id']);
           // return $model;
            $id = $model->id;
            return ['id' => $id];
        }else {

            //加载数据
            $model->load($postData);
            $model->attributes = $postData;
            //密码Hash加密处理
            $databe = $this->modelClass::find()->where(['mobile' => $postData['mobile']])->one();
            if ($databe) {
                Error('手機號碼已經註冊');
            }
            $model->mobile = $postData['mobile'];
            $model->remark = $postData['remark'];
            $model->nickname = $postData['nickname'];
            $model->name = $postData['name'];
            $model->store_id = $postData['store_id'];
            $model->roles = '['.$postData['roles'].']';
            $model->password = MD5($postData['password']);
            $model->showpassword = $postData['password'];
            //密码Hash加密处理
            // $model->password_compare = MD5($postData['password_compare']);
            //执行数据保存
            $result = $model->save();
            //return $model;
            $id = $model->id;
            return ['id' => $id];
        }

        if ($result) {
            return $result;
        }
    }



    /**
     *
     * @return [type] [description]
     */
    public function actionReset()
    {
        //调用模型
        $model    = new $this->modelClass();
        $postData = Yii::$app->request->post();
        $token    = $postData['refresh_token'] ? $postData['refresh_token'] : "";
        $token    = AccessToken::resetToken($token, 2);
        $id       = $token->getClaim('id');
        if ($id) {
            $data                  = $model::findOne($id)->toArray();
            $data['token_type']    = 'Bearer';
            $data['access_token']  = AccessToken::getToken($data['id']);
            $data['refresh_token'] = AccessToken::getToken($data['id'], 2);
            return $data;
        } else {
            return null;
        }
    }

    /**
     * 处理数据分页问题
     * @return [type] [description]
     */
    public function actionDelete()
    {
        $get        = Yii::$app->request->get();
        $modelClass = $this->modelClass;
        $id         = intval($get['id']);
        $model      = $modelClass::findOne($id);
        if ($model) {

//                $model->deleted_time = time();
//                $model->is_deleted   = 1;
                $data=['deleted_time'=>time(),'is_deleted'=>1];
                $result =  $modelClass::updateAll($data, ['id' => $id]);
                if ($result) {
                    // Yii::$app->getResponse()->setStatusCode(204);
                    return $result;
                } else {
                    throw new ForbiddenHttpException('删除失败，请检查is_deleted字段是否存在');
                }


        } else {
            throw new ForbiddenHttpException('删除失败，数据不存在');
        }
    }


    public function actionList()
    {

        //获取头部信息
        $headers = Yii::$app->getRequest()->getHeaders();
        //获取分页信息
        $pageSize = $headers->get('X-Pagination-Per-Page') ?? 20;
        $where=['is_deleted'=>0];
        $orderBy = ['created_time' => SORT_DESC];
        $accouts= Account::find()
            ->where($where)
            ->groupBy('id')
            ->orderBy($orderBy)
            ->asArray();
        var_dump($accouts);die;
        foreach ($accouts as $kb=>$veb){
            $modelClass2 = $this->modelClass2;
            $vidba =[];
            if(!empty($veb['roles'])) {
                echo $veb['roles'];die;
                $visitArray = json_decode($veb['roles'], true);
                var_dump($visitArray);die;
                $list = $modelClass2::find()->select('id,name')->where(['is_deleted' => 0])
                    ->andWhere(['in', 'id', $visitArray])->all();
                foreach ($list as $kbc => $ve) {
                    $vidba[$kbc]['id'] = $ve['id'];
                    $vidba[$kbc]['label'] = $ve['name'];
                }
                $accouts[$kb]['roles'] = $vidba;
            }
        }
        $data = new ActiveDataProvider(
            [
                'query'      => $accouts,
                'pagination' => ['pageSize' => $pageSize, 'validatePage' => false],
            ]
        );
        return $data;
    }

    /**
     * 用户菜单
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function actionMenus()
    {
        //获取角色模型
        $rolesModel = 'app\modules\roles\models\Roles';
        //获取角色模型
        $menusModel = 'app\modules\menus\models\Menus';
        //获取用户对应角色
        $roles      = json_decode(Yii::$app->user->identity->roles, true);
        $rolesArray = $rolesModel::find()->where(['is_deleted' => 0])->where(['in', 'id', $roles])->all();
        $visits     = [];
        foreach ($rolesArray as $key => $value) {
            $visitArray = json_decode($value->visits, true);
            //数组合并
            $visits = array_merge($visits, $visitArray);
        }
        //数组去重
        $visits = array_unique($visits);
        //查询菜单
        $menusArray = $menusModel::find()
        //设置菜单别名，缩短代码量
            ->alias('a')
            ->select([
                "a.id as id",
                "a.parent_id as parent_id",
                "a.modul_id as modul_id",
                "a.tag as tag",
                "a.name as name",
                "a.title as title",
                "a.is_hidden as is_hidden",
                "a.icon as icon",
                "a.type as type",
                "a.path as path",
                "a.page as page",
                "b.name as modul_name",
            ])
            ->where(['a.tag' => 'modules'])
            ->andWhere(['a.is_deleted' => 0])
            ->andWhere(['in', 'a.id', $visits])
            ->joinWith('model as b')
            ->all();
        return $menusArray;
    }

    /**
     * 用户菜单
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function actionApply()
    {
        $post = Yii::$app->request->post();
        //获取角色模型
        $rolesModel = 'app\modules\roles\models\Roles';
        //获取角色模型
        $menusModel = 'app\modules\menus\models\Menus';
        //查询获取当前菜单的所有子菜单
        $menu = $menusModel::find()->where(['is_deleted' => 0, 'name' => $post['name']])->one();

        if (!$menu) {
            Error('获取的菜单节点不存在');
        }

        //获取用户对应角色
        $roles      = json_decode(Yii::$app->user->identity->roles, true);
        $rolesArray = $rolesModel::find()->where(['is_deleted' => 0])->where(['in', 'id', $roles])->all();
        $visits     = [];
        foreach ($rolesArray as $key => $value) {
            $visitArray = json_decode($value->visits, true);
            //数组合并
            $visits = array_merge($visits, $visitArray);
        }
        //数组去重
        $visits = array_unique($visits);
        //查询菜单
        $menusArray = $menusModel::find()
        //设置菜单别名，缩短代码量
            ->alias('a')
            ->select([
                "a.id as id",
                "a.parent_id as parent_id",
                "a.modul_id as modul_id",
                "a.tag as tag",
                "a.name as name",
                "a.title as title",
                "a.is_hidden as is_hidden",
                "a.icon as icon",
                "a.type as type",
                "a.path as path",
                "a.page as page",
                "b.name as modul_name",
            ])
            ->where(['like', 'a.path', $menu['path'] . '-' . $menu['id']])
            ->andWhere(['a.is_deleted' => 0])
            ->andWhere(['in', 'a.id', $visits])
            ->joinWith('model as b')
            ->all();
        return $menusArray;
    }

    public function changePwd()
    {
        $host = Yii::$app->request->hostInfo;
        if ($host == "http://demo.leadshop.vip") {
            return true;
        }
        if ($host == "https://demo.leadshop.vip") {
            return true;
        }
        $pass     = Yii::$app->request->post('old_password');
        $newPass1 = Yii::$app->request->post('new_password1');
        $newPass2 = Yii::$app->request->post('new_password2');
        if (!$pass || !$newPass1 || !$newPass2) {
            Error('请填写表单');
        }
        if ($newPass1 != $newPass2) {
            Error('两次新密码不一致');
        }
        $admin = $this->modelClass::find()->where(['mobile' => Yii::$app->user->identity->mobile, 'password' => MD5($pass)])->one();
        if (!$admin) {
            Error('旧密码错误');
        }
        $admin->password = md5($newPass2);
        if ($admin->save()) {
            return true;
        }
        return false;
    }
}
